package com.jiusit.common;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.webbuilder.utils.FileUtil;

public class PhotoUtil {
    public static final String PHOTO_SAVE_LIST = "photolist.json";
    private static final String PICTURE_FORMAT_JPG = "jpg";

    //图片旋转
    public static void rotateImg(String imgPath, int degree, Color bgcolor) {
         try {
             File f = new File(imgPath);
             BufferedImage bufferedImage = ImageIO.read(f);
             int iw = bufferedImage.getWidth();//原始图象的宽度
             int ih = bufferedImage.getHeight();//原始图象的高度
             int w = 0;
             int h = 0;
             int x = 0;
             int y = 0;
             degree = degree % 360;
             if (degree < 0)
                degree = 360 + degree;//将角度转换到0-360度之间
             double ang = Math.toRadians(degree);//将角度转为弧度

             /**
              *确定旋转后的图象的高度和宽度
             */

             if (degree == 180 || degree == 0 || degree == 360) {
                w = iw;
                h = ih;
             } else if (degree == 90 || degree == 270) {
                w = ih;
                h = iw;
             } else {
                int d = iw + ih;
                w = (int) (d * Math.abs(Math.cos(ang)));
                h = (int) (d * Math.abs(Math.sin(ang)));
             }

             x = (w / 2) - (iw / 2);//确定原点坐标
             y = (h / 2) - (ih / 2);
             BufferedImage rotatedImage = new BufferedImage(w, h, bufferedImage.getType());
             Graphics2D gs = (Graphics2D)rotatedImage.getGraphics();
             if(bgcolor==null){
                rotatedImage  = gs.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
             }else{
                gs.setColor(bgcolor);
                gs.fillRect(0, 0, w, h);//以给定颜色绘制旋转后图片的背景
             }
             AffineTransform at = new AffineTransform();
             at.rotate(ang, w / 2, h / 2);//旋转图象
             at.translate(x, y);
             AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
             op.filter(bufferedImage, rotatedImage);
             bufferedImage = rotatedImage;
             ImageIO.write(bufferedImage, "jpg", f);
         } catch (IOException e) {
             e.printStackTrace();
         }
    }

    /**
     * 添加图片水印
     * @param targetImg 目标图片路径，如：C://myPictrue//1.jpg
     * @param waterImg  水印图片路径，如：C://myPictrue//logo.png
     * @param x 水印图片距离目标图片左侧的偏移量，如果x<0, 则在正中间
     * @param y 水印图片距离目标图片上侧的偏移量，如果y<0, 则在正中间
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
     */
    public static void pressImage(String targetImg, String waterImg, int x, int y, float alpha) {
        try {
        	
        	String real_path = waterImg.substring(0,waterImg.length()-15);
        	
            File file = new File(targetImg);
            Image image = ImageIO.read(file);
            int width = image.getWidth(null);
            int height = image.getHeight(null);

            if(width<600){
            	waterImg = real_path+"/new_icon100.png";
            }else{
            	waterImg = real_path+"/new_icon150.png";
            }
            
            /*if(width<=600){
            	waterImg = real_path+"/icon_50.png";
            }else if(width > 600 && width <=1200){
            	waterImg = real_path+"/icon.png";
            }else if(width > 1200 && width <1800){
            	waterImg = real_path+"/icon_278.png";
            }else if(width >= 1800){
            	waterImg = real_path+"/icon_512.png";
            }*/
            
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, 0, 0, width, height, null);

            Image waterImage = ImageIO.read(new File(waterImg));    // 水印文件
            int width_1 = waterImage.getWidth(null);
            int height_1 = waterImage.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            int widthDiff = width - width_1;
            int heightDiff = height - height_1;

            g.drawImage(waterImage, widthDiff-15, heightDiff-15, width_1, height_1, null); // 水印文件结束
            g.dispose();
            ImageIO.write(bufferedImage, PICTURE_FORMAT_JPG, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    /**
	 * 图片加文字水印方法一
	 * @param imgFile  图片文件路径
	 * @param text  水印文字内容
	 * @param color  文字颜色
	 * @param position  文字对齐位置 ：WM_TOP_LEFT（上左）、WM_TOP_RIGHT（上右）、
	 * WM_BOTTOM_RIGHT（下右）、WM_BOTTOM_LEFT（下左）、WM_BOTTOM_CENTER（下居中）、WM_CENTER（垂直居中）
	 * @param alpha  透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
	 * @throws Exception
	 */
	public static void addwt(String imgFile, String text, Color color,
			String fontName,String position, float alpha) throws Exception {
		File file = new File(imgFile);
		Image image = ImageIO.read(file);
		int width = image.getWidth(null);
		int height = image.getHeight(null);
		BufferedImage bufferedImage = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bufferedImage.createGraphics();
		// 字体大小数组
		int[] sizes = new int[] {40,30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10,
				8, 6, 4 };
		Font crFont = null;
		int font_width = 0;
		int font_height = 0;
		for (int i = 0; i < sizes.length; i++) {
			crFont = new Font(fontName,Font.BOLD , sizes[i]);
			g.setFont(crFont);
			FontMetrics metrics = g.getFontMetrics();
			// 获取当前字体大小在图片中的宽度和高度
			font_width = metrics.stringWidth(text);
			font_height =metrics.getHeight();
			// 判断字体的宽度是否超过图片的宽度，如果超过则切换字体，如果没有超过则退出循环
			if (font_width < width)
				break;
		}
		float xpos = 0;
		float ypos = 0;
		// 动态计算水印位置
		switch (position) {
		case "WM_TOP_LEFT":
			xpos = ((float) width * (float) .01);
			ypos = (float) height * (float) .01 +font_height;
			break;
		case "WM_TOP_RIGHT":
			xpos = ((float) width * (float) .99) - font_width;
			ypos = (float) height * (float) .01 + font_height;
			break;
		case "WM_BOTTOM_RIGHT":
			xpos = ((float) width * (float) .99) - font_width;
			ypos = ((float) height * (float) .99) - (font_height/2);
			break;
		case "WM_BOTTOM_LEFT":
			xpos = ((float) width * (float) .01);
			ypos = ((float) height * (float) .99) - (font_height/2);
			break;
		case "WM_BOTTOM_CENTER":
			xpos = ((float) width / 2)- (font_width/2);
			ypos = ((float) height * (float) .99) - (font_height/2);
			break;
		case "WM_CENTER":
			xpos = ((float) width / 2)- (font_width/2);
			ypos = ((float) height / 2);
			break;
		}
		g.drawImage(image, 0, 0, width, height, null);
		g.setColor(color);
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
				alpha));

		g.drawString(text, xpos, ypos);
		g.dispose();
		ImageIO.write(bufferedImage, PICTURE_FORMAT_JPG, file);

	}
    
    
    /**
     * 添加文字水印
     * @param targetImg 目标图片路径，如：C://myPictrue//1.jpg
     * @param pressText 水印文字， 如：中国证券网
     * @param fontName 字体名称，    如：宋体
     * @param fontStyle 字体样式，如：粗体和斜体(Font.BOLD|Font.ITALIC)
     * @param fontSize 字体大小，单位为像素 //已取消该参数
     * @param color 字体颜色
     * @param x 水印文字距离目标图片左侧的偏移量，如果x<0, 则在正中间
     * @param y 水印文字距离目标图片上侧的偏移量，如果y<0, 则在正中间
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
     */
    public static void pressText(String targetImg, String pressText, String fontName, int fontStyle, Color color, int x, int y, float alpha) {
        try {        	
            File file = new File(targetImg);
            
            Image image = ImageIO.read(file);
            
            int width = image.getWidth(null);
            int height = image.getHeight(null);

            //根据图片宽度设置文字大小begin
            int fontSize = 30;
            if(width<=500){
            	fontSize = 15;
            }else if(width > 500 && width <=1200){
            	fontSize = 30;
            }else if(width > 1200){
            	fontSize = 60;
            }
            //根据图片宽度设置文字大小end
            
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, 0, 0, width, height, null);            
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            int width_1 = fontSize * getLength(pressText);
            int height_1 = fontSize;
            int widthDiff = width - width_1;
            int heightDiff = height - height_1;
            if(x < 0){
                x = widthDiff / 2;
            }else if(x > widthDiff){
                x = widthDiff;
            }
            if(y < 0){
                y = heightDiff / 2;
            }else if(y > heightDiff){
                y = heightDiff;
            }

            g.drawString(pressText, x, y + height_1);
            g.dispose();
            ImageIO.write(bufferedImage, PICTURE_FORMAT_JPG, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取字符长度，一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
     * @param text
     * @return 字符长度，如：text="中国",返回 2；text="test",返回 2；text="中国ABC",返回 4.
     */
    public static int getLength(String text) {
        int textLength = text.length();
        int length = textLength;
        for (int i = 0; i < textLength; i++) {
            if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
                length++;
            }
        }
        return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    }

    /**
     * 图片缩放
     * @param filePath 图片路径
     * @param height 高度
     * @param width 宽度
     * @param bb 比例不对时是否需要补白
     */
    public static void resize(String filePath,String newFileSubName,int height, int width, boolean bb) {
        try {
        	//图片重命名
        	File oldfile=new File(filePath); 
            File newfile=new File(oldfile.getParent(),newFileSubName); 
  
            FileUtil.copyFile(oldfile, newfile, true, false);

            double ratio = 0; //缩放比例
            //File f = new File(newfile.getPath());
            BufferedImage bi = ImageIO.read(newfile);
            Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
            //计算比例
            height = bi.getHeight()/2;
            width = bi.getWidth()/2;
            
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue() / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                ratio = 0.5;
                AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            
            if (bb) {
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
                g.dispose();
                itemp = image;
            }
            ImageIO.write((BufferedImage) itemp, "jpg", newfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void imgQualityCompress(String inPath, String outPath, float quality) {
        try{
            File inFile = new File(inPath);
            File outFile = new File(outPath);

            BufferedImage bufferImg = ImageIO.read(inFile);
            if (bufferImg != null) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 取得内存输出流
                // 设置压缩参数
                JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam(bufferImg);
                param.setQuality(quality, false);
                param.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
                // 设置编码器
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(
                        byteArrayOutputStream, param);
                try {
                    encoder.encode(bufferImg);
                    FileOutputStream fo = new FileOutputStream(outFile);
                    fo.write(byteArrayOutputStream.toByteArray());
                    fo.flush();
                    fo.close();
                } catch (Exception e){                    
                    e.printStackTrace();
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
